/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server.listener;

import com.je.common.base.message.vo.PushMessage;
import com.je.connector.server.InstantServer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TopicListenerContainer {

    private Map<String, List<TopicListener>> topicListenerMap = new HashMap<>();

    private InstantServer instantServer;

    public TopicListenerContainer(InstantServer instantServer) {
        this.instantServer = instantServer;
    }

    public void notify(String pattern, PushMessage jmxMessageBean) {
        List<TopicListener> list = topicListenerMap.get(pattern);
        if (list == null || list.isEmpty()) {
            return;
        }
        for (TopicListener eachListenr : list) {
            eachListenr.onMessage(jmxMessageBean);
        }
    }

    public void notifyAll(PushMessage jmxMessageBean) {
        for (List<TopicListener> eachList : topicListenerMap.values()) {
            for (TopicListener eachListenr : eachList) {
                eachListenr.onMessage(jmxMessageBean);
            }
        }
    }

    public void add(TopicListener topicListener){
        List<TopicListener> inMapList;
        if (topicListenerMap.containsKey(topicListener.getPattern())) {
            inMapList = topicListenerMap.get(topicListener.getPattern());
        } else {
            inMapList = new ArrayList<>();
        }
        inMapList.add(topicListener);
        topicListenerMap.put(topicListener.getPattern(),inMapList);
    }

    public void remove(TopicListener topicListener){
        if (!topicListenerMap.containsKey(topicListener.getPattern())) {
            return;
        }
        List<TopicListener> inMapList = topicListenerMap.get(topicListener.getPattern());
        inMapList.remove(topicListener);
    }

}
